package com.misty.api.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.misty.api.service.FileService;
import com.misty.common.bean.Result;
import com.misty.common.constants.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cthulhu
 * @since 2022-11-21
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Value("${server.port}")
    private String port;

    @Value("${server.ip}")
    private String ip;

    // 定于文件上传的根路径
    private String basePath = System.getProperty("user.dir") + "/file/image/";

    /**
     *
     * @Param
     * @return
     * @Description 本地文件上传
     * @Date
     **/
    @Override
    public Result<?> upload(MultipartFile file) throws IOException {
        log.info("==========本地文件上传开始==========");
        String originalFilename = file.getOriginalFilename();
        String flag = IdUtil.fastSimpleUUID();
//        String rootFilePath = System.getProperty("user.dir");
//        String parentPath = new File(rootFilePath).getParent();
        String filePath = System.getProperty("user.dir") + "/file/image/" + flag + "_" + originalFilename ;
        File uploadFile = FileUtil.writeBytes(file.getBytes(), filePath);
        if(FileUtil.isEmpty(uploadFile)){
            return Result.error(ResultEnum.FAILURE.getValue(),"上传失败！");
        }
//        return Result.success("200","上传成功","http://" + ip + ":" + port + "/files/" + flag);
        log.info("==========本地文件上传结束==========");
        return Result.success(ResultEnum.SUCCESS.getValue(),"上传成功！","http://" + ip + ":" + port + "/files/image/" + flag);
    }


    /**
     *
     * @Param
     * @return
     * @Description 本地文件下载
     * @Date
     **/
    @Override
    public void getFiles(String flag, HttpServletResponse response) {
        log.info("==========本地文件下载开始==========");
//        OutputStream os;  // 新建一个输出流对象
        List<String> fileNames = FileUtil.listFileNames(basePath);  // 获取所有的文件名称
        String fileName = fileNames.stream()
                .filter(name -> name.contains(flag))
                .findAny().orElse("");  // 找到跟参数一致的文件
        try(
                OutputStream os = response.getOutputStream();   // 通过输出流返回文件
                ){
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);
                // 通过文件的路径读取文件字节流
                os.write(bytes);
                os.flush();
                os.close();
                response.reset();
            }
        } catch (Exception e) {
            log.info("==========本地文件下载失败==========");
        }
    }

}
